package com.tx.java8.lambda.collection.list;

import java.util.*;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;

/**
 * @author ：tx
 * @description：测试在lambda表达式中list新增的方法
 * @modified By：
 * @version:
 */
public class LambdaList {


    public static void main(String[] args) {
       // forEach();
       // removeIf();
       // replaceAll();
        sort();
    }

    /**
     * @author tx
     * @description  【forEach】
     * @param  * @Param:
     * @return void
    **/
    public static void forEach(){
        List<String> list = new ArrayList<>(Arrays.asList("php","java","best","wowowow"));
        //匿名内部类方式
        list.forEach(new Consumer<String>() {
            @Override
            public void accept(String str) {
                if(str.length() > 3){
                    System.out.println(str);
                }
            }
        });
        //lambda方式
        list.forEach(str -> {
            if(str.length() > 3){
                System.out.println(str);
            }
        });
    }


    public static void removeIf(){
        List<String> list = new ArrayList<>(Arrays.asList("php","java","best","hello"));
        //匿名内部类方式
        list.removeIf(new Predicate<String>() {
            @Override
            public boolean test(String s) {
                return s.length() == 3;
            }
        });

        //lambda方式
        list.removeIf(str -> str.length() == 5);


        //输出测试结果
        print(list);
    }

    /**
     * @author tx
     * @description  需求：假设有一个字符串列表，将其中所有长度大于3的元素转换成大写，其余元素不变。
     *                  期待结果,php,JAVA,BEST,HELLO
     * @param  * @Param: null
     * @return
    **/
    public static void replaceAll(){
        List<String> list = new ArrayList<>(Arrays.asList("php","java","best","hello"));
        //匿名内部类
        list.replaceAll(new UnaryOperator<String>() {
            @Override
            public String apply(String s) {
                if(s.length() > 3 && s.length() != 5){
                    return s.toUpperCase();
                }
                return s;
            }
        });

        //lambda表达式
        list.replaceAll(str -> {
            if(str.length() == 5){
                return str.toUpperCase();
            }
            return str;
        });

        print(list);
    }

    public static void sort(){
        List<String> list = new ArrayList<>(Arrays.asList("I","java","php","best","hello"));
        //collections方式  升序
        Collections.sort(list, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.length() - o2.length();
            }
        });

        //lambda表达式  降序
        list.sort((str1,str2) ->  str2.length() - str1.length());
        print(list);
    }


    public static void print(List list){
        list.forEach(str -> System.out.println(str));
    }
}
